﻿/*
* Irongrid for jQuery -  v1
*
* Copyright (c) 2012 Luca Gnignera 
*    https://github.com/luca-gnignera/ironGrid
*    http://code.google.com/p/irongrid/
*    
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
*/

(function ($) {
    $.addIron = function (t, p) {
        if (t.grid) return false; //return if already exist
        p = $.extend({ //apply default properties
            height: 200, //default height
            width: 'auto', //auto width
            striped: true, //apply odd even stripes
            novstripe: false,
            minwidth: 30, //min width of columns
            minheight: 80, //min height of columns
            maxWidth: null, //min width of columns
            maxHeight: null, //min height of columns
            resizable: true, //allow table resizing
            url: false, //URL if using data from AJAX
            operation: '', //operazione che si sta facendo (solo per switch esterni)
            method: 'POST', //data sending method
            returnDataType: 'xml', //type of data for AJAX, either xml or json
            sendDataType: 'xml', //type of data for AJAX, either xml or json
            errormsg: 'Errore Connessione',
            usepager: false,
            nowrap: true,
            multiSel: false,
            enableAnimation: true,
            slideUpDuration: 100,
            slideDownDuration: 100,
            page: 1, //current page
            total: 1, //total pages
            totalRows: 1, //total pages
            useRp: true, //use the results per page select box
            rp: 15, //results per page
            rpOptions: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], //allowed per-page values 
            title: false,
            pagestat: 'Visualizza {from} a {to} di {total} occorrenze',
            pagetext: 'Pagina',
            outof: 'di',
            findtext: 'Cerca',
            procmsg: 'Caricamento in corso attendere ...',
            query: null,
            qtype: '',
            nomsg: 'Nessuna occorrenza trovata',
            minColToggle: 1, //minimum allowed column to be hidden
            showColumnToggleBtn: true, //show or hide column toggle popup
            toggleTableOnStartup: false, // chiude la tabella alla partenza
            toggleTableOnTitle: false, // abilita l'papertura chiusura della tabella direttamente dal titolo
            closed: false, //indica se è chiusa la griglia
            disableOnLoad: true,
            hideOnSubmit: true,
            autoload: true,
            multiSel: false,
            enableCtrlSelection: true,
            multiFilter: false,
            fixedFilterColumnName: '',
            fixedFilterValue: '',
            fixedFilterValueType: 'text',
            fixedFilterCondition: 'AND',
            fixedFilterConditionType: 'equal',
            searchOnToolbar: false, // button search on toolbar button
            toolbarOnTop: true, // tollbar on top/bottom
            searchFieldOnTop: false, //search field on top or bottom respect container of searc button (toolbar o pager)
            blockOpacity: 0.5,
            preProcess: false,
            onDragCol: false,
            onToggleCol: false,
            onChangeSort: false,
            onSuccess: false,
            onError: false,
            onSubmit: false, //using a custom populate function
            onPressToggleGrid: false,
            onToggleFinish: false,
            autoresize: true
        }, p);
        $(t).show() //show if hidden
			.attr({
			    cellPadding: 0,
			    cellSpacing: 0,
			    border: 0
			}) //remove padding and spacing
			.removeAttr('width'); //remove width properties
        //create grid class
        var g = {
            hset: {},
            rePosDrag: function () {
                var cdleft = 0 - this.hDiv.scrollLeft;
                if (this.hDiv.scrollLeft > 0) cdleft -= Math.floor(p.cgwidth / 2);
                $(g.cDrag).css({
                    top: g.hDiv.offsetTop + 1
                });
                var cdpad = this.cdpad;
                $('div', g.cDrag).hide();
                $('thead tr:first th:visible', this.hDiv).each(function () {
                    var n = $('thead tr:first th:visible', g.hDiv).index(this);
                    var cdpos = parseInt($('div', this).width());
                    if (cdleft == 0) cdleft -= Math.floor(p.cgwidth / 2);
                    cdpos = cdpos + cdleft + cdpad;
                    if (isNaN(cdpos)) {
                        cdpos = 0;
                    }
                    $('div:eq(' + n + ')', g.cDrag).css({
                        'left': cdpos + 'px'
                    }).show();
                    cdleft = cdpos;
                });
            },
            fixHeight: function (newH) {
                newH = false;
                if (!newH) newH = $(g.bDiv).height();
                var hdHeight = $(this.hDiv).height();
                $('div', this.cDrag).each(
					function () {
					    $(this).height(newH + hdHeight);
					}
				);
                var nd = parseInt($(g.nDiv).height());
                if (nd > newH) $(g.nDiv).height(newH).width(200);
                else $(g.nDiv).height('auto').width('auto');
                $(g.block).css({
                    height: newH,
                    marginBottom: (newH * -1)
                });
                var hrH = g.bDiv.offsetTop + newH;
                if (p.height != 'auto' && p.resizable) hrH = g.vDiv.offsetTop;
                $(g.rDiv).css({
                    height: hrH
                });
            },
            dragStart: function (dragtype, e, obj) { //default drag function start
                if (dragtype == 'colresize') {//column resize
                    $(g.nDiv).hide();
                    $(g.nBtn).hide();
                    var n = $('div', this.cDrag).index(obj);
                    var ow = $('th:visible div:eq(' + n + ')', this.hDiv).width();
                    $(obj).addClass('dragging').siblings().hide();
                    $(obj).prev().addClass('dragging').show();
                    this.colresize = {
                        startX: e.pageX,
                        ol: parseInt(obj.style.left),
                        ow: ow,
                        n: n
                    };
                    $('body').css('cursor', 'col-resize');
                } else if (dragtype == 'vresize') {//table resize
                    var hgo = false;
                    $('body').css('cursor', 'row-resize');
                    if (obj) {
                        hgo = true;
                        $('body').css('cursor', 'col-resize');
                    }
                    this.vresize = {
                        h: p.height,
                        sy: e.pageY,
                        w: p.width,
                        sx: e.pageX,
                        hgo: hgo
                    };
                } else if (dragtype == 'colMove') {//column header drag
                    $(g.nDiv).hide();
                    $(g.nBtn).hide();
                    this.hset = $(this.hDiv).offset();
                    this.hset.right = this.hset.left + $('table', this.hDiv).width();
                    this.hset.bottom = this.hset.top + $('table', this.hDiv).height();
                    this.dcol = obj;
                    this.dcoln = $('th', this.hDiv).index(obj);
                    this.colCopy = document.createElement("div");
                    this.colCopy.className = "colCopy";
                    this.colCopy.innerHTML = obj.innerHTML;
                    if ($.browser.msie) {
                        this.colCopy.className = "colCopy ie";
                    }
                    $(this.colCopy).css({
                        position: 'absolute',
                        float: 'left',
                        display: 'none',
                        textAlign: obj.align
                    });
                    $('body').append(this.colCopy);
                    $(this.cDrag).hide();
                }
                $('body').noSelect();
            },
            dragMove: function (e) {
                if (this.colresize) {//column resize
                    var n = this.colresize.n;
                    var diff = e.pageX - this.colresize.startX;
                    var nleft = this.colresize.ol + diff;
                    var nw = this.colresize.ow + diff;
                    if (nw > p.minwidth) {
                        $('div:eq(' + n + ')', this.cDrag).css('left', nleft);
                        this.colresize.nw = nw;
                    }
                } else if (this.vresize) {//table resize
                    var v = this.vresize;
                    var y = e.pageY;
                    var diff = y - v.sy;
                    if (!p.defwidth) p.defwidth = p.width;
                    if (p.width != 'auto' && !p.nohresize && v.hgo) {
                        var x = e.pageX;
                        var xdiff = x - v.sx;
                        var newW = v.w + xdiff;
                        if (newW > p.defwidth) {
                            this.gDiv.style.width = newW + 'px';
                            p.width = newW;
                        }
                    }
                    var newH = v.h + diff;
                    if (((newH > p.minheight || p.height < p.minheight) && !v.hgo)
                    || ((newH > p.minheight || p.height < p.minheight) && !v.hgo && p.autoresize)) {
                        this.bDiv.style.height = newH + 'px';
                        p.height = newH;
                        this.fixHeight(newH);
                    }
                    v = null;
                } else if (this.colCopy) {
                    $(this.dcol).addClass('thMove').removeClass('thOver');
                    if (e.pageX > this.hset.right || e.pageX < this.hset.left || e.pageY > this.hset.bottom || e.pageY < this.hset.top) {
                        //this.dragEnd();
                        $('body').css('cursor', 'move');
                    } else {
                        $('body').css('cursor', 'pointer');
                    }
                    $(this.colCopy).css({
                        top: e.pageY + 10,
                        left: e.pageX + 20,
                        display: 'block'
                    });
                }
            },
            dragEnd: function () {
                if (this.colresize) {
                    var n = this.colresize.n;
                    var nw = this.colresize.nw;
                    $('th:visible div:eq(' + n + ')', this.hDiv).css('width', nw);
                    $('tr', this.bDiv).each(
						function () {
						    $('td:visible div:eq(' + n + ')', this).css('width', nw);
						}
					);
                    this.hDiv.scrollLeft = this.bDiv.scrollLeft;
                    $('div:eq(' + n + ')', this.cDrag).siblings().show();
                    $('.dragging', this.cDrag).removeClass('dragging');
                    this.rePosDrag();
                    this.fixHeight();
                    this.colresize = false;
                } else if (this.vresize) {
                    this.vresize = false;
                    if (p.onTableResize) {
                        p.onTableResize();
                    }
                } else if (this.colCopy) {
                    $(this.colCopy).remove();
                    if (this.dcolt != null) {
                        if (this.dcoln > this.dcolt) $('th:eq(' + this.dcolt + ')', this.hDiv).before(this.dcol);
                        else $('th:eq(' + this.dcolt + ')', this.hDiv).after(this.dcol);
                        this.switchCol(this.dcoln, this.dcolt);
                        $(this.cdropleft).remove();
                        $(this.cdropright).remove();
                        this.rePosDrag();
                        if (p.onDragCol) {
                            p.onDragCol(this.dcoln, this.dcolt);
                        }
                    }
                    this.dcol = null;
                    this.hset = null;
                    this.dcoln = null;
                    this.dcolt = null;
                    this.colCopy = null;
                    $('.thMove', this.hDiv).removeClass('thMove');
                    $(this.cDrag).show();
                }
                $('body').css('cursor', 'default');
                $('body').noSelect(false);
            },
            toggleCol: function (cid, visible) {
                var ncol = $("th[axis='col" + cid + "']", this.hDiv)[0];
                var n = $('thead th', g.hDiv).index(ncol);
                var cb = $('input[value=' + cid + ']', g.nDiv)[0];
                if (visible == null) {
                    visible = ncol.hidden;
                }
                if ($('input:checked', g.nDiv).length < p.minColToggle && !visible) {
                    return false;
                }
                if (visible) {
                    ncol.hidden = false;
                    $(ncol).show();
                    cb.checked = true;
                } else {
                    ncol.hidden = true;
                    $(ncol).hide();
                    cb.checked = false;
                }
                $('tbody tr', t).each(
					function () {
					    if (visible) {
					        $('td:eq(' + n + ')', this).show();
					    } else {
					        $('td:eq(' + n + ')', this).hide();
					    }
					}
				);
                this.rePosDrag();
                if (p.onToggleCol) {
                    p.onToggleCol(cid, visible);
                }
                $(g.nDiv).hide();
                $(g.nBtn).hide();
                return visible;
            },
            switchCol: function (cdrag, cdrop) { //switch columns
                $('tbody tr', t).each(
					function () {
					    if (cdrag > cdrop) $('td:eq(' + cdrop + ')', this).before($('td:eq(' + cdrag + ')', this));
					    else $('td:eq(' + cdrop + ')', this).after($('td:eq(' + cdrag + ')', this));
					}
				);
                //switch order in nDiv
                if (cdrag > cdrop) {
                    $('tr:eq(' + cdrop + ')', this.nDiv).before($('tr:eq(' + cdrag + ')', this.nDiv));
                } else {
                    $('tr:eq(' + cdrop + ')', this.nDiv).after($('tr:eq(' + cdrag + ')', this.nDiv));
                }
                if ($.browser.msie && $.browser.version < 7.0) {
                    $('tr:eq(' + cdrop + ') input', this.nDiv)[0].checked = true;
                }
                this.hDiv.scrollLeft = this.bDiv.scrollLeft;
            },
            scroll: function (e) {
                this.hDiv.scrollLeft = this.bDiv.scrollLeft;
                // rallentava lo scroll non so perchè lo chiamava
                //this.rePosDrag();
            },
            addData: function (data) { //parse data
                this.disable(false);
                //alert(data);
                if (p.returnDataType == 'json') {
                    data = $.extend({ rows: [], page: 0, total: 0 }, data);
                }
                if (p.preProcess) {
                    data = p.preProcess(data);
                }
                $('.pReload', this.pDiv).removeClass('loading');
                this.loading = false;
                if (!data) {
                    $('.pPageStat', this.pDiv).html(p.errormsg);
                    return false;
                }
                if (p.returnDataType == 'xml') {
                    p.total = +$('rows total', data).text();
                    p.totalRows = +$('rows totalRows', data).text();
                    //alert(p.totalRows);
                } else {
                    p.total = data.total;
                }
                if (p.total == 0) {
                    $('tr, a, td, div', t).unbind();
                    $(t).empty();
                    p.pages = 1;
                    p.page = 1;
                    this.buildpager();
                    $('.pPageStat', this.pDiv).html(p.nomsg);
                    //se non ci sono righe cmq faccio finire la procedura con on success
                    if (p.onSuccess) {
                        p.onSuccess(this);
                    }
                    return false;
                }
                p.pages = Math.ceil(p.total / p.rp);

                if (p.returnDataType == 'xml') {
                    p.page = +$('rows page', data).text();
                } else {
                    p.page = data.page;
                }
                this.buildpager();
                //build new body
                var tbody = document.createElement('tbody');
                tbody.id = 'ironGridtBody';

                if (p.returnDataType == 'json') {
                    $.each(data.rows, function (i, row) {
                        var tr = document.createElement('tr');
                        if (i % 2 && p.striped) {
                            tr.className = 'erow';
                        }
                        if (row.id) {
                            tr.id = 'row' + row.id;
                        }
                        $('thead tr:first th', g.hDiv).each( //add cell
							function () {
							    var td = document.createElement('td');
							    var idx = $(this).attr('axis').substr(3);
							    td.align = this.calign;
							    // If the json elements aren't named (which is typical), use numeric order
							    if (typeof row.cell[idx] != "undefined") {
							        td.innerHTML = (row.cell[idx] != null) ? row.cell[idx] : ''; //null-check for Opera-browser
							    } else {
							        td.innerHTML = row.cell[p.colModel[idx].name];
							    }
							    $(td).attr('abbr', $(this).attr('abbr'));
							    $(tr).append(td);
							    td = null;
							}
						);
                        if ($('thead', this.gDiv).length < 1) {//handle if grid has no headers
                            for (idx = 0; idx < cell.length; idx++) {
                                var td = document.createElement('td');
                                // If the json elements aren't named (which is typical), use numeric order
                                if (typeof row.cell[idx] != "undefined") {
                                    td.innerHTML = (row.cell[idx] != null) ? row.cell[idx] : ''; //null-check for Opera-browser
                                } else {
                                    td.innerHTML = row.cell[p.colModel[idx].name];
                                }
                                $(tr).append(td);
                                td = null;
                            }
                        }
                        $(tbody).append(tr);
                        tr = null;
                    });
                } else if (p.returnDataType == 'xml') {
                    // aggiungo le righe tutte insieme
                    var rows = "";
                    var xml = "";
                    if (jQuery.isXMLDoc(data)) {
                        xml = $('rows row', data).text();
                    } else {
                        //xml = data.xml.substring(data.xml.indexOf('</totalRows>') + 12, data.xml.indexOf('</rows>')).replace(/row/g, 'tr').replace(/<cell>/g, '<td style="display:none"><div>').replace(/<\/cell>/g, '</div></td>');
                        xml = data.xml;
                    }

                    rows = xml;

                    $(tbody).append(rows);
                    var idxColumn = 0;
                    $('tr', g.bDiv).remove();
                    // gestione eventi su riga
                    $('tr', tbody).click(function (e) {
                        //alert('click dentro addRowProp');
                        var obj = (e.target || e.srcElement);
                        if (obj.href || obj.type) return true;
                        $(this).focus();

                        $(this).toggleClass('trSelected');
                        if (!p.multiSel) $(this).siblings().removeClass('trSelected');
                        firstRowSelected = $('.trSelected :first', $(this).parent()).parent().prevAll().length

                        // ciclo dal primo selezionato fino a quello su cui è stato fatto click e li rendo selezionati
                        if (p.multiSel && p.enableCtrlSelection) {
                            if (e.ctrlKey) {
                                for (i = firstRowSelected; i < row; i++) {
                                    $('tbody tr', g.bDiv).eq(i).addClass('trSelected');
                                }
                            }
                        }
                        // non uso lo shift per il multi select, perchè mi seleziona tutte le label del documento
                        if (e.shiftKey) {

                        }
                    }).mousedown(function (e) {
                        //                        if (e.shiftKey) {
                        //                            $(this).toggleClass('trSelected');
                        //                            g.multiSel = true;
                        //                            this.focus();
                        //                            $(g.gDiv).noSelect();
                        //                        }
                    }).mouseup(function () {
                        //                        if (g.multisel) {
                        //                            g.multiSel = false;
                        //                            $(g.gDiv).noSelect(false);
                        //                        }
                    }).hover(function (e) {
                        //                        if (g.multiSel) {
                        //                            $(this).toggleClass('trSelected');
                        //                        }
                    }, function () { });
                    if ($.browser.msie && $.browser.version < 7.0) {
                        $(this).hover(function () {
                            $(this).addClass('trOver');
                        }, function () {
                            $(this).removeClass('trOver');
                        });
                    }

                    // aggiungo la classname per tutte le righe dispari
                    if (p.striped) {
                        $('tr:even', tbody).addClass('erow');
                    }

                    // metto lo stile per la colonna sortata
                    if (p.sortname) {
                        idxColumn = $('th', g.hDiv).index($('th[id="' + p.sortname + '"]', g.hDiv))
                        $('td:eq(' + idxColumn + ')', $('tr', tbody)).addClass('sorted');
                    }

                    //sostituisco le celle vuote con un tab
                    $('td div:empty', tbody).html('&nbsp;');
                    //aggiungo il nowrap
                    if (p.nowrap == false) {
                        $('td div', tbody).css('white-space', 'normal');
                    }

                    //ciclo su tutte le colonne visibili per farle riapparire
                    //vengono create tutte display none per evitare il doppio ciclo uno questo ed uno per nascondere quelle 
                    // nascoste. Imposto la grandezza del div e l'allineamento. inoltre se è un'immagine creo l'immagine
                    // uso il filtro perchè se la tabella è chiusa di default th:visible è uguale a 0 quindi quando apro non vedo le righe riempite
                    //$('th:visible', g.hDiv).each(function () { 
                            $('th', g.hDiv).filter(function () { return $(this).css("display") != "none" }).each(function(){
                        var th = $(this)
                        idxColumn = $('th', g.hDiv).index(this)

                        // imposto il css e l'id per tutti i td
                        $('td:eq(' + idxColumn + ')', $('tr', tbody)).css({
                            display: 'table-cell',
                            textAlign: $(th).attr('calign'),
                            width: $('div:first', $(th))[0].style.width
                        }).attr('abbr', $(th).attr('id')).attr('id', 'td' + $(th).attr('id') + idxColumn)

                        // imposto il css e l'id per tutti i div del td
                        var $tds = $('#td' + $(th).attr('id') + idxColumn + ' div', tbody);
                        $tds.css({
                            display: 'block',
                            textAlign: $(th).attr('calign'),
                            width: $('div:first', $(th))[0].style.width
                        }).attr('abbr', $(th).attr('id')).attr('id', 'div' + $(th).attr('id') + idxColumn);

                        //gestisco le colonne di tipo image
                        if ($(th)[0].image == true) {
                            var $divs = $('#div' + $(th).attr('id') + idxColumn, tbody);
                            $divs.each(function () {
                                var $cel = $(this).parent();
                                var $div = $(this);
                                var $img = document.createElement('img');

                                $img.id = 'img_' + idxColumn;
                                $img.src = p.colModel[idxColumn].imageThumbsUrl + $(this).text();
                                $img.imageUrl = p.colModel[idxColumn].imageUrl + $(this).text();
                                $img.imageWidth = p.colModel[idxColumn].imageWidth
                                $img.imageHeight = p.colModel[idxColumn].imageHeight
                                $img.border = 0
                                $img.width = p.colModel[idxColumn].imageThumbsWidth.replace('px', '');
                                $img.height = p.colModel[idxColumn].imageThumbsHeight.replace('px', '');
                                $img.align = p.colModel[idxColumn].imageAlign
                                $img.title = p.colModel[idxColumn].imageTitle
                                $div.empty().append($img);

                                // se è richiesta l'ingrandimento dell'immagine al mouse over faccio anche il delegato
                                if (p.colModel[idxColumn].enlargeOnMouseOver != undefined && p.colModel[idxColumn].enlargeOnMouseOver) {
                                    xOffset = 10;
                                    yOffset = 30;

                                    $cel.delegate("img", "mouseover mouseout", function (e) {
                                        if (e.type == 'mouseover') {
                                            this.t = $(this).attr('title');
                                            this.title = "";
                                            var c = (this.t != "") ? "<br/>" + this.t : "";
                                            var p = document.createElement('p');
                                            var $img = document.createElement('img');
                                            p.id = 'preview';

                                            $img.src = $(this).attr('imageUrl');
                                            $img.alt = "Image preview";
                                            $img.width = $(this).attr('imageWidth').replace('px', '');
                                            $img.height = $(this).attr('imageHeight').replace('px', '');

                                            $(p).append($img);
                                            $(p).append(c);
                                            $("body").append(p);
                                            //                                            $("body").append('<p id="preview"><img src="' + $(this).attr('imageUrl') + '" alt="Image preview" ' +
                                            //                        '" width="' + $(this).attr('imageWidth') + '"' +
                                            //                        '" height="' + $(this).attr('imageHeight') + '"' +
                                            //                        '/>' + c + '</p>');
                                            $("#preview", p).css({
                                                zindex: '9999999999',
                                                position: 'absolute',
                                                top: (parseFloat(e.pageY) - parseFloat(xOffset)) + "px",
                                                left: (parseFloat(e.pageX) - parseFloat(yOffset)) + "px"
                                            }).fadeIn("fast");
                                        } else {
                                            this.title = this.t;
                                            $("#preview", p).remove();
                                        }
                                    });

                                    $cel.delegate("img", "mousemove", function (e) {
                                        //alert($("#preview").attr('id'/));
                                        $("#preview").css({
                                            top: (e.pageY - xOffset) + "px",
                                            left: (e.pageX + yOffset) + "px"
                                        });
                                    });
                                } // fine if ingrandimento immagine
                            }); // fine ciclo div
                        } // fine if image

                    });

                }
                //alert('proseguo')
                $('tr', t).unbind();
                $(t).empty();

                $(t).append(tbody); //aggiunge i dati della tabella
                //this.addCellProp();
                //this.addRowProp();
                this.rePosDrag();
                //                // fa il resize della tabella in base alle righe che trova                
                //                if (p.autoresize) {
                //                    var nHeitgh = $(tbody, t).css('height').replace('px', '')
                //                    //se esiste la scrollbar di sotto aggiungo 20 px
                //                    //if ($(g.bDiv).get(0).scrollHeight > $(g.bDiv).width()) {
                //                    nHeitgh = parseFloat(parseFloat(nHeitgh) + 20);
                //                    //}
                //                    p.height = parseFloat(nHeitgh);
                //                    p.minheight = p.height;
                //                    $(g.bDiv).animate({
                //                        height: p.height + "px"
                //                    }, p.slideUpDuration);
                //                }
                g.resize();
                tbody = null;
                data = null;

                i = null;
                if (p.onSuccess) {
                    p.onSuccess(this);
                }
                if (p.hideOnSubmit) {
                    $(g.block).remove();
                }
                this.hDiv.scrollLeft = this.bDiv.scrollLeft;
                if ($.browser.opera) {
                    $(t).css('visibility', 'visible');
                }
            },
            changeSort: function (th) { //change sortorder
                if (this.loading) {
                    return true;
                }
                $(g.nDiv).hide();
                $(g.nBtn).hide();
                if (p.sortname == $(th).attr('abbr')) {
                    if (p.sortorder == 'asc') {
                        p.sortorder = 'desc';
                    } else {
                        p.sortorder = 'asc';
                    }
                }
                $(th).addClass('sorted').siblings().removeClass('sorted');
                $('.sdesc', this.hDiv).removeClass('sdesc');
                $('.sasc', this.hDiv).removeClass('sasc');
                $('div', th).addClass('s' + p.sortorder);
                p.sortname = $(th).attr('abbr');
                if (p.onChangeSort) {
                    p.onChangeSort(p.sortname, p.sortorder);
                } else {
                    this.populate();
                }
            },
            buildpager: function () { //rebuild pager based on new properties
                $('.pcontrol input', this.pDiv).val(p.page);
                $('.pcontrol span', this.pDiv).html(p.pages);
                var r1 = (p.page - 1) * p.rp + 1;
                var r2 = r1 + p.rp - 1;
                if (p.total < r2) {
                    r2 = p.total;
                }
                var stat = p.pagestat;
                stat = stat.replace(/{from}/, r1);
                stat = stat.replace(/{to}/, r2);
                stat = stat.replace(/{total}/, p.total);
                stat = stat.replace(/{totalRows}/, p.totalRows);
                $('.pPageStat', this.pDiv).html(stat);
            },
            populate: function () { //get latest data
                this.disable(p.disableOnLoad);
                if (this.loading) {
                    return true;
                }
                if (p.onSubmit) {
                    var gh = p.onSubmit();
                    if (!gh) {
                        return false;
                    }
                }
                this.loading = true;
                if (!p.url) {
                    return false;
                }
                $('.pPageStat', this.pDiv).html(p.procmsg);
                $('.pReload', this.pDiv).addClass('loading');
                $(g.block).css({
                    top: g.bDiv.offsetTop
                });
                if (p.hideOnSubmit) {
                    $(this.gDiv).prepend(g.block);
                }
                if ($.browser.opera) {
                    $(t).css('visibility', 'hidden');
                }
                if (!p.newp) {
                    p.newp = 1;
                }
                if (p.page > p.pages) {
                    p.page = p.pages;
                }

                //alert(p.url);
                /// luca creazione parametri ingrsso procedura
                var contentType = ''
                if (p.sendDataType == "json") {
                    var filters1 = new Array();
                    $.extend(filters1, p.query);
                    if (p.fixedFilterColumnName != '') {
                        if (filters1 == null) { filters1 = new Array() }
                        var filter = {
                            ColumnName: p.fixedFilterColumnName,
                            Value: p.fixedFilterValue,
                            ValueType: p.fixedFilterValueType,
                            Condition: p.fixedFilterCondition,
                            ConditionType: p.fixedFilterConditionType
                        };
                        filters1.push(filter);
                    }
                    var param = {
                        page: p.newp,
                        rp: p.rp,
                        sortname: p.sortname,
                        sortorder: p.sortorder,
                        query: filters1,
                        qtype: p.qtype,
                        buttonRefreshPressed: p.buttonRefreshPressed
                    };

                    if (p.params) {
                        for (var pi = 0; pi < p.params.length; pi++) {
                            param[p.params[pi].name] = p.params[pi].value
                        }
                    }


                    var finalParam =
                {
                    jsonSendParameters: param
                }
                    $('body').css('cursor', 'progress')

                    //provajson
                    $.ajax({
                        type: p.method,
                        url: p.url,
                        data: JSON.stringify(finalParam),
                        dataType: p.returnDataType,
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            g.addData(data);
                            $('body').css('cursor', 'auto')
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            $('body').css('cursor', 'auto')
                            try {
                                if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
                            } catch (e) { }
                        }
                    });
                }
                else {
                    // chiamata normale i parametri page etc si devono prendere con request.form
                    var param = [{
                        name: 'page',
                        value: p.newp
                    }, {
                        name: 'rp',
                        value: p.rp
                    }, {
                        name: 'sortname',
                        value: p.sortname
                    }, {
                        name: 'sortorder',
                        value: p.sortorder
                    }, {
                        name: 'query',
                        value: p.query
                    }, {
                        name: 'qtype',
                        value: p.qtype
                    }, {
                        name: 'buttonRefreshPressed',
                        value: p.buttonRefreshPressed
                    }];
                    if (p.params) {
                        for (var pi = 0; pi < p.params.length; pi++) {
                            param[param.length] = p.params[pi];
                        }
                    }
                    $('body').css('cursor', 'progress')
                    $.ajax({
                        type: p.method,
                        url: p.url,
                        data: param,
                        dataType: p.returnDataType,
                        success: function (data) {
                            g.addData(data);
                            $('body').css('cursor', 'auto')
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            $('body').css('cursor', 'auto')
                            try {
                                if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
                            } catch (e) { }
                        }
                    });
                }
                contentType = "application/json; charset=utf-8";
                /*
                $.ajax({
                type: p.method,
                url: p.url,
                data: param,
                dataType: p.dataType,
                contentType: contentType,
                success: function (data) {
                g.addData(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                try {
                if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
                } catch (e) { }
                }
                });
                */
                p.buttonRefreshPressed = false;
            },
            doSearch: function () {
                //// luca creazione filtro dinamico
                if (p.multiFilter) {
                    var filters = new Array()
                    $('#searchType > div[id*="divContenuto"]', g.sDiv).each(function () {
                        //filters[$(this).val()] = $('input[name=q]', g.sDiv).val();
                        var filter = {}
                        var div = $('.ironGridcontent', this) //$('#searchType > div[id="divContenuto' + $(this).val() + '"] .ironGridcontent')
                        var condition = $('.condition select', div)

                        var txt = $('.field input[type="text"]', div)
                        var cmb = $('.field select option:selected', div)
                        var opt = $('.field input[type="radio"]:checked', div)
                        var chk = $('.field input[type="checkbox"]:checked', div)
                        var finalObj = undefined;

                        if (txt.get(0)) { finalObj = txt }
                        if (cmb.get(0)) { finalObj = cmb }
                        if (opt.get(0)) { finalObj = opt }
                        if (chk.get(0)) { finalObj = chk }

                        filter['Condition'] = condition.is(":visible") ? condition.val() : '';
                        filter['ColumnName'] = finalObj.attr('columnName');
                        filter['Value'] = finalObj.val();
                        filter['ValueType'] = finalObj.attr('valueType');
                        filter['ConditionType'] = finalObj.attr('conditionType');

                        filters.push(filter)
                    });
                    p.query = filters;

                } else {
                    p.query = $('input[name=q]', g.sDiv).val();
                    p.qtype = $('select[name=qtype]', g.sDiv).val();
                }

                p.newp = 1;
                this.populate();
            },
            doClearSearch: function () {
                p.query = null;
                $(g.sDiv).slideToggle('fast', function () {
                    p.newp = 1;
                    g.populate();
                });
            },
            changePage: function (ctype) { //change page
                if (this.loading) {
                    return true;
                }
                switch (ctype) {
                    case 'first':
                        p.newp = 1;
                        break;
                    case 'prev':
                        if (p.page > 1) {
                            p.newp = parseInt(p.page) - 1;
                        }
                        break;
                    case 'next':
                        if (p.page < p.pages) {
                            p.newp = parseInt(p.page) + 1;
                        }
                        break;
                    case 'last':
                        p.newp = p.pages;
                        break;
                    case 'input':
                        var nv = parseInt($('.pcontrol input', this.pDiv).val());
                        if (isNaN(nv)) {
                            nv = 1;
                        }
                        if (nv < 1) {
                            nv = 1;
                        } else if (nv > p.pages) {
                            nv = p.pages;
                        }
                        $('.pcontrol input', this.pDiv).val(nv);
                        p.newp = nv;
                        break;
                }
                if (p.newp == p.page) {
                    return false;
                }
                if (p.onChangePage) {
                    p.onChangePage(p.newp);
                } else {
                    this.populate();
                }
            },
            addCellProp: function () {
                $('tbody tr td', g.bDiv).each(function () {
                    var tdDiv = document.createElement('div');
                    var n = $('td', $(this).parent()).index(this);
                    var pth = $('th:eq(' + n + ')', g.hDiv).get(0);
                    if (pth != null) {
                        if (p.sortname == $(pth).attr('abbr') && p.sortname) {
                            this.className = 'sorted';
                        }
                        $(tdDiv).css({
                            textAlign: pth.calign,
                            width: $('div:first', pth)[0].style.width
                        });
                        if (pth.hidden) {
                            $(this).css('display', 'none');
                        }
                    }
                    if (p.nowrap == false) {
                        $(tdDiv).css('white-space', 'normal');
                    }
                    if (this.innerHTML == '') {
                        this.innerHTML = '&nbsp;';
                    }
                    tdDiv.innerHTML = this.innerHTML;
                    var prnt = $(this).parent()[0];
                    var pid = false;
                    if (prnt.id) {
                        pid = prnt.id.substr(3);
                    }
                    if (pth != null) {
                        if (pth.process) pth.process(tdDiv, pid);
                    }
                    $(this).empty().append(tdDiv).removeAttr('width'); //wrap content
                });
            },
            getCellDim: function (obj) {// get cell prop for editable event
                var ht = parseInt($(obj).height());
                var pht = parseInt($(obj).parent().height());
                var wt = parseInt(obj.style.width);
                var pwt = parseInt($(obj).parent().width());
                var top = obj.offsetParent.offsetTop;
                var left = obj.offsetParent.offsetLeft;
                var pdl = parseInt($(obj).css('paddingLeft'));
                var pdt = parseInt($(obj).css('paddingTop'));
                return {
                    ht: ht,
                    wt: wt,
                    top: top,
                    left: left,
                    pdl: pdl,
                    pdt: pdt,
                    pht: pht,
                    pwt: pwt
                };
            },
            addRowProp: function () {
                $('tbody tr', g.bDiv).each(function () {
                    col = 0;
                    row = 0;
                    firstRowSelected = 0;
                    $('td', $(this)).click(function () {
                        $(this).focus();
                        col = $(this).parent().children().index($(this));
                        row = $(this).parent().parent().children().index($(this).parent());
                        // altro modo di trovare riga e colonna
                        //col = $(this).prevAll().length;
                        //row = $(this).parent('tr').prevAll().length;
                    });
                    $(this).click(function (e) {
                        //alert('click dentro addRowProp');
                        var obj = (e.target || e.srcElement);
                        if (obj.href || obj.type) return true;
                        $(this).focus();

                        $(this).toggleClass('trSelected');
                        if (!p.multiSel) $(this).siblings().removeClass('trSelected');
                        firstRowSelected = $('.trSelected :first', $(this).parent()).parent().prevAll().length

                        // ciclo dal primo selezionato fino a quello su cui è stato fatto click e li rendo selezionati
                        if (p.multiSel && p.enableCtrlSelection) {
                            if (e.ctrlKey) {
                                for (i = firstRowSelected; i < row; i++) {
                                    $('tbody tr', g.bDiv).eq(i).addClass('trSelected');
                                }
                            }
                        }
                        // non uso lo shift per il multi select, perchè mi seleziona tutte le label del documento
                        if (e.shiftKey) {

                        }
                    }).mousedown(function (e) {
                        //                        if (e.shiftKey) {
                        //                            $(this).toggleClass('trSelected');
                        //                            g.multiSel = true;
                        //                            this.focus();
                        //                            $(g.gDiv).noSelect();
                        //                        }
                    }).mouseup(function () {
                        //                        if (g.multisel) {
                        //                            g.multiSel = false;
                        //                            $(g.gDiv).noSelect(false);
                        //                        }
                    }).hover(function (e) {
                        //                        if (g.multiSel) {
                        //                            $(this).toggleClass('trSelected');
                        //                        }
                    }, function () { });
                    if ($.browser.msie && $.browser.version < 7.0) {
                        $(this).hover(function () {
                            $(this).addClass('trOver');
                        }, function () {
                            $(this).removeClass('trOver');
                        });
                    }
                });
            },
            disableTopButton: function (disable) { // function to reload grid
                $('.fbutton', $('#ironGridToolbar', g.gDiv)).attr('disabled', disable);
            }, //end disableButton
            disableSearch: function (disable) { // function to reload grid
                $('input, select, div', $('.searchContainer', g.sDiv)).attr('disabled', disable);
            }, //end disableButton
            disablePager: function (disable) { // function to reload grid
                $('.pFirst', g.pDiv).attr('disabled', disable);
                $('.pPrev', g.pDiv).attr('disabled', disable);
                $('.pNext', g.pDiv).attr('disabled', disable);
                $('.pLast', g.pDiv).attr('disabled', disable);
                $('.pReload', g.pDiv).attr('disabled', disable);
                $('select[name="rp"]', g.pDiv).attr('disabled', disable);
                $('#txtGoPage', g.pDiv).attr('disabled', disable);
                $('.pSearch', g.pDiv).attr('disabled', disable);
            }, //end DisablePager
            disable: function (disable) { // function to reload grid
                this.disableTopButton(disable)
                this.disableSearch(disable)
                this.disablePager(disable)
            }, //end disable
            slideToggle: function (idx) {
                var name = '';
                var current = undefined;
                var countDiv = $(g.gDiv).children('#ironGridBody, #ironGridToolbar, #ironGridPager, #ironGridSearch, #ironGridHeader, #ironGridBody').length - 1;
                var duration = p.slideDownDuration
                var addValue = 1;

                //vedo a quale div sono arrivato
                if (p.closed) {
                    //se devo chiudere parto dall'ultimo div
                    if (idx == undefined) { idx = countDiv; }
                    countDiv = 0;
                    addValue = -1
                } else {
                    //se devo aprire parto dal primo div fino all'ultimo
                    if (idx == undefined) {
                        idx = 0;
                        $(g.gDiv).stop(true).toggleClass('hideBody');
                    }
                }

                current = $(g.gDiv).children('#ironGridBody, #ironGridToolbar, #ironGridPager, #ironGridSearch, #ironGridHeader, #ironGridBody')[idx]
                name = $(current).attr('id');

                //if ($.isNumeric(duration) && name == 'ironGridBody') { duration -= 100 }
                if (p.closed) {
                    if (idx < 0) { $(g.gDiv).stop(true).toggleClass('hideBody'); g.resize(); return };
                } else {
                    if (idx > countDiv) { g.resize(); return };
                }

                if (name == 'ironGridPager' && !p.usepager) {//se il non esistepager esiste salto
                    idx += addValue;
                    g.slideToggle(idx);
                } else {
                    if (name == 'ironGridSearch' && !$(g.sDiv)[0].open) { //se la rierca non era stata aperta salto
                        idx += addValue;
                        g.slideToggle(idx);
                    } else {
                        $(current).animate({
                            opacity: 'toggle',
                            height: 'toggle'
                        }, duration, function () {
                            idx += addValue;
                            g.slideToggle(idx);
                        });
                    }
                }
            }, // end slideToggle
            resize: function () {
                // fa il resize della tabella in base alle righe che trova                
                if (!p.closed) {
                    if (p.autoresize) {
                        var nHeitgh = $(t).css('height');  ///$(g.bDiv).css('height').replace('px', '')
                        //se esiste la scrollbar di sotto aggiungo 20 px
                        //if ($(g.bDiv).get(0).scrollHeight > $(g.bDiv).width()) {
                        nHeitgh = parseFloat(parseFloat(nHeitgh) + 30);
                        //}
                        if (parseFloat(p.maxHeight) < parseFloat(nHeitgh)) {
                            nHeitgh = parseFloat(p.maxHeight);
                        }
                        p.height = parseFloat(nHeitgh);
                        p.minheight = p.height;
                        $(g.bDiv).animate({
                            height: p.height + "px"
                        }, p.slideUpDuration);
                    }
                }
            },
            createCascadeMenu: function (menu) {
                ///aaaaaaaaaaaa
                /*
                <div id="divMenu">
                <ul id='ironGridCascadeMenu'>
                <li class='ironGridCascadeMenuLiTop'><a href='/EProgram/Home.aspx' class='ironGridCascadeMenuTop_link'><span>Home</span></a> </li>
                <li class='ironGridCascadeMenuLiTop'><a href='#' class='ironGridCascadeMenuTop_link'><span class='ironGridCascadeMenuDown'>Area Amministrazione</span></a>
                <ul class='ironGridCascadeMenuSub'>
                <li><a href='/EProgram/Admin/GestioneTabelleBase.aspx'>Tabelle Di Base</a> </li>
                <li><a href='#' class='fly'>Altro Menu</a>
                <ul>
                <li><a href='#' class='fly'>Sotto Altro Menu</a>
                <ul>
                <li><a href='#' class='fly'>Sotto Sotto Altro Menu</a>
                <ul>
                <li><a href='#'>Sotto Sotto Altro Menu</a> </li>
                <li><a href='#'>Sotto Sotto Altro Menu</a> </li>
                <li><a href='#'>Sotto Sotto Altro Menu</a> </li>
                <li><a href='#'>Sotto Sotto Altro Menu</a> </li>
                <li><a href='#'>Sotto Sotto Altro Menu</a> </li>
                </ul>
                </li>
                </ul>
                </li>
                </ul>
                </li>
                </ul>
                </li>
                </ul>
                </div>
                */
                var bDivMenu = document.createElement('div');
                var ulMenu = document.createElement('ul');
                var liMenu = document.createElement('li');
                var anchor = document.createElement('a');
                var span = document.createElement('span');

                bDivMenu.className = 'menu'
                bDivMenu.id = menu.id;
                bDivMenu.name = menu.id;

                ulMenu.className = 'ironGridCascadeMenu'
                liMenu.className = 'ironGridCascadeMenuLiTop'
                anchor.className = 'ironGridCascadeMenuTop_link'
                if (menu.bclass) $(span).addClass(menu.bclass).css({
                    paddingLeft: 20
                });

                liMenu.title = menu.toolTip;


                //bDivMenu.className = menu.bclass;

                //anchor.href = '#nogo'
                span.innerHTML = menu.label;
                $(anchor).append(span);
                $(liMenu).append(span);

                if (menu.leaves.length > 0) {
                    span.className = 'ironGridCascadeMenuDown'
                    $(liMenu).append(g.createSubMenu(menu.leaves));
                }

                $(ulMenu).append(liMenu);
                $(bDivMenu).append(ulMenu);
                return bDivMenu;
            },
            createSubMenu: function (leaves) {
                var subUlMenu = document.createElement('ul');
                subUlMenu.className = 'ironGridCascadeMenuSub'

                for (mnu in leaves) {
                    var subLliMenu = document.createElement('li');
                    var subAnchor = document.createElement('a');
                    var mnuCurrent = leaves[mnu]
                    var subSpan = document.createElement('span');

                    subLliMenu.title = mnuCurrent.toolTip;

                    subAnchor.href = mnuCurrent.href

                    subSpan.innerHTML = mnuCurrent.label;
                    $(subAnchor).append(subSpan);
                    $(subLliMenu).append(subAnchor);

                    if (mnuCurrent.leaves != undefined) {
                        subAnchor.className = 'fly'
                        $(subLliMenu).append(g.createSubMenu(mnuCurrent.leaves));
                    }
                    $(subUlMenu).append(subLliMenu);
                }
                return subUlMenu;

            },
            pager: 0
        }; // fine create grid

        if (p.colModel) { //create model if any
            thead = document.createElement('thead');
            var tr = document.createElement('tr');
            for (var i = 0; i < p.colModel.length; i++) {
                var cm = p.colModel[i];
                var th = document.createElement('th');
                th.undrag = cm.undragable ? true : false; //undragable
                th.unsize = cm.unresizeable ? true : false;

                th.align = cm.headerAlign ? cm.headerAlign : 'center'; //alignment
                th.calign = cm.align ? cm.align : 'left'; //alignment

                th.innerHTML = cm.display;
                if (cm.name && cm.sortable) {
                    $(th).attr('abbr', cm.name);
                }
                $(th).attr('id', cm.name);
                $(th).attr('abbr', cm.name);

                $(th).attr('axis', 'col' + i);
                if (cm.align) {
                    //th.align = cm.align;
                    th.calign = cm.align;
                }
                if (cm.width) {
                    $(th).attr('width', cm.width);
                }
                th.hidden = false;
                if ($(cm).attr('hide')) { //colonna nascosta
                    th.hidden = true;
                }
                th.image = false;
                if ($(cm).attr('image')) { //colonna nascosta
                    th.image = true;
                }

                th.title = '';
                if ($(cm).attr('tooltip') != '') { //tooltip colonna
                    th.title = $(cm).attr('tooltip');
                }

                if (cm.process) {
                    th.process = cm.process;
                }
                $(tr).append(th); // appende le signole intestazioni
            }
            $(thead).append(tr); //appende tutta la riga dell'intestazioni colonne
            $(t).prepend(thead); // appende la tabella intestazioni su t
        } // end if p.colmodel
        //init divs
        g.gDiv = document.createElement('div'); //create global container
        g.mDiv = document.createElement('div'); //create title container
        g.hDiv = document.createElement('div'); //create header container
        g.bDiv = document.createElement('div'); //create body container

        g.vDiv = document.createElement('div'); //create grip
        g.rDiv = document.createElement('div'); //create horizontal resizer
        g.cDrag = document.createElement('div'); //create column drag
        g.block = document.createElement('div'); //creat blocker
        g.nDiv = document.createElement('div'); //create column show/hide popup
        g.nBtn = document.createElement('div'); //create column show/hide button
        g.iDiv = document.createElement('div'); //create editable layer
        g.tDiv = document.createElement('div'); //create toolbar
        g.sDiv = document.createElement('div'); //create searc container
        g.pDiv = document.createElement('div'); //create pager container

        g.mDiv.id = 'ironGridTitleBar'
        g.hDiv.id = 'ironGridHeader'
        g.bDiv.id = 'ironGridBody'
        g.tDiv.id = 'ironGridToolbar';
        g.sDiv.id = 'ironGridSearch';
        g.pDiv.id = 'ironGridPager';

        if (!p.usepager) {
            g.pDiv.style.display = 'none';
        }
        g.hTable = document.createElement('table');
        g.gDiv.className = 'irongrid';
        if (p.width != 'auto') {
            g.gDiv.style.width = p.width + 'px';
        }
        //add conditional classes
        if ($.browser.msie) {
            $(g.gDiv).addClass('ie');
        }
        if (p.novstripe) {
            $(g.gDiv).addClass('novstripe');
        }
        //aggiunge l'intestazione delle colonne
        $(t).before(g.gDiv);
        $(g.gDiv).append(t);
        //set toolbar
        if (p.toolBarButtons) {
            g.tDiv.className = 'tDiv';
            var tDiv2 = document.createElement('div');
            tDiv2.className = 'tDiv2';
            for (var i = 0; i < p.toolBarButtons.length; i++) {
                var btn = p.toolBarButtons[i];
                if (btn.menu) { // bottone menu
                    //aaaaaaaaaaaaaa
                    $(tDiv2).append(g.createCascadeMenu(btn));
                } else {
                    if (!btn.separator) {
                        var btnDiv = document.createElement('div');
                        var span = document.createElement('span');

                        btnDiv.className = 'fbutton';
                        if (btn.onpress) { btnDiv.onpress = btn.onpress; }
                        if (btn.name != undefined && btn.name != '') { btnDiv.name = btn.name; }
                        if (btn.id != undefined && btn.id != '') { btnDiv.id = btn.id; }
                        if (btn.toolTip != undefined && btn.toolTip != '') { btnDiv.title = btn.toolTip; }

                        if (btn.labelId != undefined && btn.labelId != '') { span.id = btn.labelId; }
                        if (btn.labelName != undefined && btn.labelName != '') { span.name = btn.labelName; }
                        if (btn.label != undefined && btn.label != '') { span.innerHTML = btn.label; }

                        if (btn.type != undefined
                        && btn.type == 'checkbox') {
                            //creo il cechk box
                            var chk = document.createElement("input")
                            if (btn.chkId != undefined && btn.chkId != '') { chk.id = btn.chkId; }
                            if (btn.chkName != undefined && btn.chkName != '') { chk.name = btn.chkName; }
                            chk.value = btn.value;
                            chk.title = btn.toolTip;
                            chk.type = 'checkbox';
                            chk.checked = btn.checked;
                            chk.onpress = btn.onpress;

                            $(btnDiv).append(chk).append(span);
                        } else {
                            $(btnDiv).append(span);
                        }
                        //$(btnDiv).append(span).append(chk);

                        if (btn.bclass) $('span', btnDiv).addClass(btn.bclass).css({
                            paddingLeft: 20
                        });

                        if (btn.onpress) {
                            if (btn.type != undefined
                            && btn.type == 'checkbox') {
                                //click su check box
                                $(chk).click(function (e) {
                                    this.onpress(this, g.gDiv);
                                    // fermo la propagazione degli eventi altrimenti mi parte anche il click sul div
                                    e.stopPropagation()
                                })


                            }

                            //click su div
                            $(btnDiv).click(function () {
                                if ($('input[type="checkbox"]', $(this)).length > 0) {
                                    $('input[type="checkbox"]', $(this)).attr('checked', $('input[type="checkbox"]', $(this)).attr('checked') != 'checked');
                                }
                                //this.onpress(this.id, g.gDiv);
                                this.onpress(this, $('.trSelected', g.gDiv));
                            });
                        }
                        $(tDiv2).append(btnDiv); // aggiunge il bottone
                        if ($.browser.msie && $.browser.version < 7.0) {
                            $(btnDiv).hover(function () {
                                $(this).addClass('fbOver');
                            }, function () {
                                $(this).removeClass('fbOver');
                            });
                        }
                        if (btn.hide) {
                            $(btnDiv).hide();
                        }
                    } else {
                        $(tDiv2).append("<div class='btnseparator'></div>"); //aggiunge il separatore dei bottoni
                    }
                }
            } // fine for


            /* // aggiungo il menu li
            var btnDiv1 = document.createElement('div');
            var span1 = document.createElement('span');
            var ul = document.createElement('ul');
            var li = document.createElement('li');
            var ah = document.createElement('a');
            var li = document.createElement('li');
            li.innerHTML = 'prova prova'
            var li1 = document.createElement('li');
            li1.innerHTML = 'prova prova1'
            var li2 = document.createElement('li');
            li2.innerHTML = 'prova prova2'
            var li3 = document.createElement('li');
            li3.innerHTML = 'prova prova3'
            span1.innerHTML = 'asdjasdas'
            $(ul).append(li).append(li1).append(li2).append(li3)
            $(btnDiv1).append(ul).append(span1);
            
            $(tDiv2).append(btnDiv1)
            */
            $(g.tDiv).append(tDiv2);
            //$(g.tDiv).css('height', '1080px');
            $(g.tDiv).append("<div style='clear:both'></div>");
            // appende il toolbar sopra la griglia o sotto (prima del pager)
            if (p.toolbarOnTop) {
                $(g.gDiv).prepend(g.tDiv);
            } else {
                $(g.gDiv).append(g.tDiv);
            }
        }



        /*




        if (p.checks) {
        g.tDiv.className = 'tDiv';
        var tDiv2 = document.createElement('div');
        tDiv2.className = 'tDiv2';
        for (var i = 0; i < p.checks.length; i++) {
        var btn = p.checks[i];
        if (!btn.separator) {
        var btnDiv = document.createElement('div');
        btnDiv.className = 'fbutton';

        btnDiv.innerHTML = "<div><input type='checkbox' id='" + btn.id + "' checked='" + btn.checked + "' /></div>";
        if (btn.bclass) $('input[type="checkbox"]', btnDiv).addClass(btn.bclass).css({
        paddingLeft: 20
        });
        btnDiv.onpress = btn.onpress;
        btnDiv.name = btn.name;
        btnDiv.title = btn.toolTip;
        if (btn.onpress) {
        $('input[type="checkbox"]', btnDiv).click(function () {
        alert('click');
        this.onpress(this.id, g.gDiv);
        //alert(this.name);
        });
        }
        $(tDiv2).append(btnDiv);
        if ($.browser.msie && $.browser.version < 7.0) {
        $(btnDiv).hover(function () {
        $(this).addClass('fbOver');
        }, function () {
        $(this).removeClass('fbOver');
        });
        }
        if (btn.hide) {
        $(btnDiv).hide();
        }
        } else {
        $(tDiv2).append("<div class='btnseparator'></div>");
        }
        }
        $(g.tDiv).append(tDiv2);
        $(g.tDiv).append("<div style='clear:both'></div>");
        $(g.gDiv).prepend(g.tDiv);
        }
        */

        g.hDiv.className = 'hDiv';

        //inserisce le intestazioni nella tabella vuota BHOOO
        $(t).before(g.hDiv);

        g.hTable.cellPadding = 0;
        g.hTable.cellSpacing = 0;
        $(g.hDiv).append('<div class="hDivBox"></div>');
        $('div', g.hDiv).append(g.hTable);

        var thead = $("thead:first", t).get(0);
        if (thead) $(g.hTable).append(thead); // aggiunge la tabella delle intestazioni nel div hTable
        thead = null;
        if (!p.colmodel) var ci = 0;

        //gestisce gli eventi delle intestazioni
        $('thead tr:first th', g.hDiv).each(function () {
            var thdiv = document.createElement('div');
            if ($(this).attr('abbr')) {
                //click intestazione per ordinamento
                $(this).click(function (e) {
                    // click intestazione
                    if (!$(this).hasClass('thOver')) return false;
                    var obj = (e.target || e.srcElement);
                    if (obj.href || obj.type) return true;
                    g.changeSort(this);
                });
                if ($(this).attr('abbr') == p.sortname) {
                    this.className = 'sorted';
                    thdiv.className = 's' + p.sortorder;
                }
            }
            if (this.hidden) {
                $(this).hide();
            }
            if (!p.colmodel) {
                $(this).attr('axis', 'col' + ci++);
            }
            $(thdiv).css({
                textAlign: this.align,
                width: this.width + 'px'
            });
            thdiv.innerHTML = this.innerHTML;
            var me = this;
            if (me.undrag) me.style.cursor = 'default';
            $(this).empty().append(thdiv).removeAttr('width').mousedown(function (e) {
                if (!me.undrag) { g.dragStart('colMove', e, this); } //undragable
            }).hover(function () {
                //undragable
                if (me.undrag) {
                    $(g.nDiv).hide();
                    $(g.nBtn).hide();
                    return
                };
                if (!g.colresize && !$(this).hasClass('thMove') && !g.colCopy) {
                    $(this).addClass('thOver');
                }
                if ($(this).attr('abbr') != p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) {
                    $('div', this).addClass('s' + p.sortorder);
                } else if ($(this).attr('abbr') == p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) {
                    var no = (p.sortorder == 'asc') ? 'desc' : 'asc';
                    $('div', this).removeClass('s' + p.sortorder).addClass('s' + no);
                }
                if (g.colCopy) {
                    var n = $('th', g.hDiv).index(this);
                    if (n == g.dcoln) {
                        return false;
                    }
                    if (n < g.dcoln) {
                        $(this).append(g.cdropleft);
                    } else {
                        $(this).append(g.cdropright);
                    }
                    g.dcolt = n;
                } else if (!g.colresize) {
                    // header onmouseover
                    var nv = $('th:visible', g.hDiv).index(this);
                    var onl = parseInt($('div:eq(' + nv + ')', g.cDrag).css('left'));
                    var nw = jQuery(g.nBtn).outerWidth();
                    var nl = onl - nw + Math.floor(p.cgwidth / 2);

                    $(g.nDiv).hide();
                    $(g.nBtn).hide();
                    $(g.nBtn).css({
                        'left': nl,
                        top: g.hDiv.offsetTop
                    }).show();
                    var ndw = parseInt($(g.nDiv).width());
                    $(g.nDiv).css({
                        top: g.bDiv.offsetTop
                    });
                    if ((nl + ndw) > $(g.gDiv).width()) {
                        $(g.nDiv).css('left', onl - ndw + 1);
                    } else {
                        $(g.nDiv).css('left', nl);
                    }
                    if ($(this).hasClass('sorted')) {
                        $(g.nBtn).addClass('srtd');
                    } else {
                        $(g.nBtn).removeClass('srtd');
                    }
                }
            }, function () {
                // onmouse out delle intestazion
                $(this).removeClass('thOver');

                if ($(this).attr('abbr') != p.sortname) {
                    $('div', this).removeClass('s' + p.sortorder);
                } else if ($(this).attr('abbr') == p.sortname) {
                    var no = (p.sortorder == 'asc') ? 'desc' : 'asc';
                    $('div', this).addClass('s' + p.sortorder).removeClass('s' + no);
                }
                if (g.colCopy) {
                    $(g.cdropleft).remove();
                    $(g.cdropright).remove();
                    g.dcolt = null;
                }
            }); //wrap content
        }); //fine gestione eventi intestazione

        //set bDiv
        g.bDiv.className = 'bDiv';
        $(t).before(g.bDiv);  //bdiv vuoto
        var timeStamp, lengthStamp = (new Date()).getTime();
        $(g.bDiv).css({
            height: (p.height == 'auto') ? 'auto' : p.height + "px"
        }).scroll(function (e) {
            g.scroll()
            var now = (new Date()).getTime();

            if (now - lengthStamp > 400) {
                $(this).trigger('scrollStart');
                lengthStamp = now;
            }
            //solo allo scroll ebd faccio partire il reposdrag
            clearTimeout(timeStamp);
            timeStamp = setTimeout(function () {
                $(g).trigger('scrollEnd');
                g.rePosDrag();
            }, 300);
        }).append(t);

        if (p.height == 'auto') {
            $('table', g.bDiv).addClass('autoht');
        }
        //add td & row properties
        //g.addCellProp();
        //g.addRowProp();
        //set cDrag
        var cdcol = $('thead tr:first th:first', g.hDiv).get(0);
        if (cdcol != null) {
            g.cDrag.className = 'cDrag';
            g.cdpad = 0;
            g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderLeftWidth'))) ? 0 : parseInt($('div', cdcol).css('borderLeftWidth')));
            g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderRightWidth'))) ? 0 : parseInt($('div', cdcol).css('borderRightWidth')));
            g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingLeft'))) ? 0 : parseInt($('div', cdcol).css('paddingLeft')));
            g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingRight'))) ? 0 : parseInt($('div', cdcol).css('paddingRight')));
            g.cdpad += (isNaN(parseInt($(cdcol).css('borderLeftWidth'))) ? 0 : parseInt($(cdcol).css('borderLeftWidth')));
            g.cdpad += (isNaN(parseInt($(cdcol).css('borderRightWidth'))) ? 0 : parseInt($(cdcol).css('borderRightWidth')));
            g.cdpad += (isNaN(parseInt($(cdcol).css('paddingLeft'))) ? 0 : parseInt($(cdcol).css('paddingLeft')));
            g.cdpad += (isNaN(parseInt($(cdcol).css('paddingRight'))) ? 0 : parseInt($(cdcol).css('paddingRight')));
            $(g.bDiv).before(g.cDrag);
            var cdheight = $(g.bDiv).height();
            var hdheight = $(g.hDiv).height();
            $(g.cDrag).css({
                top: -hdheight + 'px'
            });
            $('thead tr:first th', g.hDiv).each(function () {
                var me = this;
                if (!me.hidden) {
                    var cgDiv = document.createElement('div');
                    cgDiv.unsize = me.unsize;
                    $(g.cDrag).append(cgDiv);
                    p.cgwidth = 0;
                    if (!p.cgwidth) {
                        p.cgwidth = $(cgDiv).width();
                    }
                    // col resize
                    if (!me.unsize) {
                        $(cgDiv).css({
                            height: cdheight + hdheight
                        }).mousedown(function (e) {
                            g.dragStart('colresize', e, this);
                        });
                    }
                    else {
                        cgDiv.className = 'noresize';
                    }

                    if ($.browser.msie && $.browser.version < 7.0) {
                        g.fixHeight($(g.gDiv).height());
                        $(cgDiv).hover(function () {
                            g.fixHeight();
                            $(this).addClass('dragging')
                        }, function () {
                            if (!g.colresize) $(this).removeClass('dragging')
                        });
                    }
                }
            });
        }
        //add strip
        if (p.striped) {
            $('tbody tr:odd', g.bDiv).addClass('erow');
        }
        if (p.resizable && p.height != 'auto') {
            g.vDiv.className = 'vGrip';
            $(g.vDiv).mousedown(function (e) {
                g.dragStart('vresize', e)
            }).html('<span></span>');
            $(g.bDiv).after(g.vDiv);
        }
        if (p.resizable && p.width != 'auto' && !p.nohresize) {
            g.rDiv.className = 'hGrip';
            $(g.rDiv).mousedown(function (e) {
                g.dragStart('vresize', e, true);
            }).html('<span></span>').css('height', $(g.gDiv).height());
            if ($.browser.msie && $.browser.version < 7.0) {
                $(g.rDiv).hover(function () {
                    $(this).addClass('hgOver');
                }, function () {
                    $(this).removeClass('hgOver');
                });
            }
            $(g.gDiv).append(g.rDiv); // bo aggiunge uno span
        }
        // add pager
        if (p.usepager) {
            g.pDiv.className = 'pDiv';
            g.pDiv.innerHTML = '<div class="pDiv2"></div>';
            if (p.toolbarOnTop) {
                $(g.bDiv).after(g.pDiv); //pager on bottom of body
            } else {
                $(g.gDiv).append(g.pDiv); //pager after tollbar
            }

            var html = ' <div class="pGroup"> <div class="pFirst pButton"><span></span></div><div class="pPrev pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"><span class="pcontrol">' + p.pagetext + ' <input id="txtGoPage" type="text" size="4" value="1" /> ' + p.outof + ' <span> 1 </span></span></div> <div class="btnseparator"></div> <div class="pGroup"> <div class="pNext pButton"><span></span></div><div class="pLast pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"> <div class="pReload pButton"><span></span></div> </div> <div class="btnseparator"></div> <div class="pGroup"><span class="pPageStat"></span></div>';
            $('div', g.pDiv).html(html);

            $('.pReload', g.pDiv).click(function () {
                // chiamata in più al bottone refresh
                p.buttonRefreshPressed = true;
                if (p.onPressRefresh != undefined
                && p.onPressRefresh != '') {
                    this.onpress = p.onPressRefresh;
                    this.onpress(this, g.gDiv);
                }
                // auto submit sul bottone refresh
                if (p.autoSubmitOnRefresh != undefined
                && p.autoSubmitOnRefresh == true) { g.populate(); }
            });
            $('.pFirst', g.pDiv).click(function () {
                g.changePage('first')
            });
            $('.pPrev', g.pDiv).click(function () {
                g.changePage('prev')
            });
            $('.pNext', g.pDiv).click(function () {
                g.changePage('next')
            });
            $('.pLast', g.pDiv).click(function () {
                g.changePage('last')
            });
            $('.pcontrol input', g.pDiv).keydown(function (e) {
                if (e.keyCode == 13) g.changePage('input')
            });
            if ($.browser.msie && $.browser.version < 7) $('.pButton', g.pDiv).hover(function () {
                $(this).addClass('pBtnOver');
            }, function () {
                $(this).removeClass('pBtnOver');
            });
            if (p.useRp) {
                var opt = '',
					sel = '';
                for (var nx = 0; nx < p.rpOptions.length; nx++) {
                    if (p.rp == p.rpOptions[nx]) sel = 'selected="selected"';
                    else sel = '';
                    opt += "<option value='" + p.rpOptions[nx] + "' " + sel + " >" + p.rpOptions[nx] + "&nbsp;&nbsp;</option>";
                } // aggiunge i bottoni del pager la combo della selezione righe per pagina
                $('.pDiv2', g.pDiv).prepend("<div class='pGroup'><select name='rp'>" + opt + "</select></div> <div class='btnseparator'></div>");
                $('select', g.pDiv).change(function () {
                    if (p.onRpChange) {
                        p.onRpChange(+this.value);
                    } else {
                        p.newp = 1;
                        p.rp = +this.value;
                        g.populate();
                    }
                });
            }
            //add search button
        }

        if (p.searchParameters) {
            var pSearchWhere = g.pDiv;
            if (p.searchOnToolbar) {
                $('.tDiv2', g.tDiv).prepend("<div class='fButton'><div class='pSearch'><span></span></div> </div>  <div class='btnseparator'></div>");
                pSearchWhere = g.tDiv;
            } else {
                $('.pDiv2', g.pDiv).prepend("<div class='pGroup'> <div class='pSearch pButton'><span></span></div> </div>  <div class='btnseparator'></div>");
            }

            $('.pSearch', pSearchWhere).click(function () {
                $(g.sDiv).slideToggle('fast', function () {
                    $('.sDiv:visible select:first', g.gDiv).trigger('focus');
                    this.open = $(g.sDiv).is(':visible');
                });
            });
            //add search box
            g.sDiv.className = 'sDiv';
            var sitems = p.searchParameters.items;
            var sopt = "<option value=''></option>", sel = '';
            $(g.sDiv).append("<div class='searchContainer'>" +
                                    "<div>" +
                                        "<div id='searchFor' class='searchFor'></div>" +
                                        "<div id='searchButtons' class='searchButtons'></div>" +
                                    "</div>" +
                                    "<div id='searchType' class='searchType'></div>" +
                                 "</div>");

            for (var s = 0; s < sitems.length; s++) {
                //                    if (p.qtype == '' && sitems[s].isdefault == true) {
                //                        p.qtype = sitems[s].value;
                //                        sel = 'selected="selected"';
                //                    } else {
                //                        sel = '';
                //                    }

                var removeClass = ''
                var sID = sitems[s].id;
                var sLabel = sitems[s].label;
                var sType = sitems[s].type;
                var sValue = sitems[s].value;
                var sName = sitems[s].name;
                var sColumnName = sitems[s].columnName;
                var sValueType = sitems[s].valueType;
                var sExcluzive = sitems[s].excluzive;
                var sToolTip = sitems[s].toolTip;
                var sDisplay = sitems[s].display;
                var sConditionType = sitems[s].conditionType;
                var sItem = null;

                if (p.searchParameters.buttonRemoveClass) { removeClass = 'class="' + p.searchParameters.buttonRemoveClass + '" style="padding-left: 20px"' + removeClass + '>' }
                var remover = '<div class="fbutton" id="remove' + sID + '" tag="' + sID + '"><span ' + removeClass + p.searchParameters.buttonRemoveText + '</span></div>'
                var condition = '<div class="condition"><select id="condition' + sID + '" ><option>And</option><option>Or</option></select></div>'
                var container = '<div class="container" id="divContenuto' + sID + '">'
                var content = '<div class="ironGridcontent">' + condition + '<span class="fieldLabel">' + sLabel + '</span>'

                switch (sType) {
                    // campo testo                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
                    case 'text':
                        content += '<div class="field">' +
                                            '<input type="text" id="' + sID + '" value="' + sValue + '" name="' + sName + '" columnName="' + sColumnName + '" valueType="' + sValueType + '" conditionType="' + sConditionType + '"/>' +
                                        '</div>'
                        break;
                    case 'dropdown':
                        content += '<div class="field"><select id="' + sID + '">'
                        for (var s1 = 0; s1 < sitems[s].items.length; s1++) {
                            sItem = sitems[s].items[s1]
                            if (sItem.isdefault == true) {
                                sel = 'selected="selected"';
                            } else {
                                sel = '';
                            }
                            content += '<option value="' + sItem.value + '" ' + sel + '  name="' + sName + '" columnName="' + sItem.columnName + '" valueType="' + sItem.valueType + '" conditionType="' + sItem.conditionType + '">' + sItem.display + '</option>';
                        }
                        content += '</select></div>'
                        break;
                    case 'option':
                        var name = sName;
                        content += '<div class="field">'

                        if (sExcluzive) { name = sID; }
                        for (var s1 = 0; s1 < sitems[s].items.length; s1++) {
                            sItem = sitems[s].items[s1];
                            if (sItem.isdefault == true) {
                                sel = 'checked';
                            } else {
                                sel = '';
                            }
                            if (sItem.preDisplay) {
                                content += sItem.label + '<input type="radio" id="' + sItem.id + '" name="' + name + '" ' + sel + ' value="' + sItem.value + '"  columnName="' + sItem.columnName + '" valueType="' + sItem.valueType + '" conditionType="' + sItem.conditionType + '"/>'
                            } else {
                                content += '<input type="radio" id="' + sItem.id + '" name="' + name + '" ' + sel + ' value="' + sItem.value + '" columnName="' + sItem.columnName + '" valueType="' + sItem.valueType + '" conditionType="' + sItem.conditionType + '"/>' + sItem.label
                            }
                        }
                        content += '</div>'
                        break;
                    case 'checkbox':
                        content += '<div class="field">'
                        for (var s1 = 0; s1 < sitems[s].items.length; s1++) {
                            sItem = sitems[s].items[s1]
                            if (sItem.isdefault == true) {
                                sel = 'checked';
                            } else {
                                sel = '';
                            }
                            if (sItem.preDisplay) {
                                content += sItem.label + '<input type="checkbox" id="' + sItem.id + '" ' + sel + ' value="' + sItem.value + '" name="' + sName + '" columnName="' + sItem.columnName + '" valueType="' + sItem.valueType + '" conditionType="' + sItem.conditionType + '"/>'
                            } else {
                                content += '<input type="checkbox" id="' + sItem.id + '" ' + sel + ' value="' + sItem.value + '" name="' + sName + '" columnName="' + sItem.columnName + '" valueType="' + sItem.valueType + '" conditionType="' + sItem.conditionType + '"/>' + sItem.label
                            }
                        }

                        content += '</div>'
                        break;
                }
                container += content + remover + '</div></div>'
                sopt += "<option rowId='" + s + "' context='" + container + "' value='" + sID + "' " + sel + " title='" + sToolTip + "'>" + sDisplay + "</option>";
            }

            if (p.qtype == '') {
                p.qtype = sitems[0].value;
            }

            $('#searchFor', g.sDiv).prepend(p.findtext + " <select name='qtype' id='qtype'>" + sopt + "</select>");
            $('#qtype', g.sDiv).change(function () {
                $('#searchType', g.sDiv).append($("option[value='" + $(this).val() + "']").attr('context'))
                $("option[value='" + $(this).val() + "']", g.sDiv).attr('disabled', true);

                //mi salvo l'id riga della combo mi serve dopo per non passare la and o la or alla prima riga
                $('#searchType > div[id*=divContenuto]:last', g.sDiv).attr('rowID', $("option[value='" + $(this).val() + "']", g.sDiv).attr('rowID'))

                // aggancio il click sui div rimuovi filtro
                $('div[id="remove' + $(this).val() + '"]', g.sDiv).click(function (e) {
                    // rimuovo il div contenente il campo di ricerca
                    $("#divContenuto" + $(this).attr('tag'), g.sDiv).remove();

                    //nascondo la prima combo di condizione and/or
                    $('#searchType' + ' > div:first select[id*="condition"]', g.sDiv).hide();

                    // riabilito l'option nella select
                    $("option[value='" + $(this).attr('tag') + "']", g.sDiv).attr('disabled', false);

                    // se ci sta una ricerca sola la prima la porto nuovamente tutta a destra perchè non ci sta più nessuna combo and or
                    if ($('#searchType', g.sDiv).find('div[id*="divContenuto"]').length == 1) {
                        $('#searchType' + ' > div:first .fieldLabel', g.sDiv).css('padding-left', '0px')
                    } else {
                        $('#searchType' + ' > div:first .fieldLabel', g.sDiv).css('padding-left', $('#searchType' + ' > div .condition', g.sDiv).css('width'))
                    }
                });

                if ($('#searchType', g.sDiv).find('div[id*="divContenuto"]').length > 1) {
                    // se i filtri sono più di uno sposto il primo più a destra considernado la grandezza della combo and or
                    $('#searchType' + ' > div:first .fieldLabel', g.sDiv).css('padding-left', $('#searchType' + ' > div .condition', g.sDiv).css('width'))
                    $('#condition' + $(this).val(), g.sDiv).show()
                }

                $(this).val('');
            })
            //aggiungo il bottone della ricerca
            if (p.buttonFind != undefined) {
                var btnDivFind = document.createElement('div');
                btnDivFind.className = 'fbutton';
                if (p.buttonFind.onpress != undefined) { btnDivFind.onpress = p.buttonFind.onpress; }
                if (p.buttonFind.name != undefined && p.buttonFind.name != '') { btnDivFind.name = p.buttonFind.name; }
                if (p.buttonFind.id != undefined && p.buttonFind.id != '') { btnDivFind.id = p.buttonFind.id; }
                if (p.buttonFind.toolTip != undefined && p.buttonFind.toolTip != '') { btnDivFind.title = p.buttonFind.toolTip; }

                btnDivFind.innerHTML = "<div><span>" + p.buttonFind.label + "</span></div>";

                if (p.buttonFind.bclass) $('span', btnDivFind).addClass(p.buttonFind.bclass).css({
                    paddingLeft: 20
                });

                $(btnDivFind).click(function () {
                    if (p.buttonFind.onpress) { this.onpress(this, g.gDiv); }
                    g.doSearch();
                });
                $('#searchButtons', g.sDiv).append(btnDivFind);
                if ($.browser.msie && $.browser.version < 7.0) {
                    $(btnDivFind).hover(function () {
                        $(this).addClass('fbOver');
                    }, function () {
                        $(this).removeClass('fbOver');
                    });
                }
            }

            if (p.buttonClearFind != undefined) {
                var btnDivClear = document.createElement('div');
                btnDivClear.className = 'fbutton';
                if (p.buttonClearFind.onpress != undefined) { btnDivClear.onpress = p.buttonClearFind.onpress; }
                if (p.buttonClearFind.name != undefined && p.buttonClearFind.name != '') { btnDivClear.name = p.buttonClearFind.name; }
                if (p.buttonClearFind.id != undefined && p.buttonClearFind.id != '') { btnDivClear.id = p.buttonClearFind.id; }
                if (p.buttonClearFind.toolTip != undefined && p.buttonClearFind.toolTip != '') { btnDivClear.title = p.buttonClearFind.toolTip; }

                btnDivClear.innerHTML = "<div><span>" + p.buttonClearFind.label + "</span></div>";

                if (p.buttonClearFind.bclass) $('span', btnDivClear).addClass(p.buttonClearFind.bclass).css({
                    paddingLeft: 20
                });

                $(btnDivClear).click(function () {
                    if (p.buttonClearFind.onpress) { this.onpress(this, g.gDiv); }
                    //rimuovo tutti i filtri di ricerca
                    $('#searchType > div', g.sDiv).remove();
                    // riabilito i valori della combo di ricerca
                    $("option", $('#searchFor', g.sDiv)).attr('disabled', false);
                    g.doClearSearch();
                });
                $('#searchButtons', g.sDiv).append(btnDivClear);
                if ($.browser.msie && $.browser.version < 7.0) {
                    $(btnDivClear).hover(function () {
                        $(this).addClass('fbOver');
                    }, function () {
                        $(this).removeClass('fbOver');
                    });
                }
            }

            $('input[value=Clear]', g.sDiv).click(function () {
                $('input[name=q]', g.sDiv).val('');
                p.query = '';
                g.doSearch();
            });

            // appende la ricerca prima o dopo la lista dei dati
            var searchWhere = g.pDiv
            if (p.searchOnToolbar) {
                searchWhere = g.tDiv
            }

            if (p.searchFieldOnTop) {
                $(searchWhere).before(g.sDiv); // aggiunge il div della ricerca
            } else {
                $(searchWhere).after(g.sDiv); // aggiunge il div della ricerca
            }
        }

        // $(g.pDiv, g.sDiv).append("<div style='clear:both; background-color:black;'></div>");
        // add title

        if (p.title) {
            var classTitle = 'ftitle';
            var toggleButton = 'div.ptogtitle';
            if (p.toggleTableOnTitle) {
                classTitle = 'ftitlePointer';
                toggleButton += ', div.ftitlePointer';
            }

            g.mDiv.className = 'mDiv';
            g.mDiv.innerHTML = '<div class="' + classTitle + '">' + p.title + '</div>';
            // aggiunta titolo
            $(g.gDiv).prepend(g.mDiv); //titolo

            if (p.showTableToggleBtn) {
                $(g.mDiv).append('<div class="ptogtitle" title="Minimize/Maximize Table"><span></span></div>');

                //$('div.ptogtitle, div.ftitle' ,  g.mDiv).click(function () {
                $(toggleButton, g.mDiv).click(function (event) {
                    event.stopPropagation();
                    var classClosed = 'irongrid ie hideBody';

                    //se è nascosto imposto l'attributo toggled a true
                    classClosed = 'irongrid ie'
                    p.closed = false;
                    if ($(g.gDiv).attr('class') == classClosed) {
                        p.closed = true;
                    }
                    if (p.onPressToggleGrid != undefined
                    && p.onPressToggleGrid != '') {
                        this.onpress = p.onPressToggleGrid;
                        this.onpress(this, g.mDiv);
                    }

                    //abilita l'animazione sul toggle
                    if (p.enableAnimation) {
                        g.slideToggle();
                    } else { // ramo no animazione
                        $(g.gDiv).toggleClass('hideBody');
                    }
                    $(toggleButton, g.mDiv).toggleClass('vsble');
                    //questa è la chiamata alla eventuale funzione dichiarata all'estenro, è messa in tutti e tre i rami
                    // delle if erche devepartire dopo laq fine animazione
                    if (p.onToggleFinish != undefined && p.onToggleFinish != '') {
                        this.onpress = p.onToggleFinish;
                        this.onpress(this, g.mDiv);
                    }
                });
            }
        }

        //setup cdrops
        g.cdropleft = document.createElement('span');
        g.cdropleft.className = 'cdropleft';
        g.cdropright = document.createElement('span');
        g.cdropright.className = 'cdropright';
        //add block
        g.block.className = 'gBlock';
        var gh = $(g.bDiv).height();
        var gtop = g.bDiv.offsetTop;
        $(g.block).css({
            width: g.bDiv.style.width,
            height: gh,
            background: 'white',
            position: 'relative',
            marginBottom: (gh * -1),
            zIndex: 1,
            top: gtop,
            left: '0px'
        });
        $(g.block).fadeTo(0, p.blockOpacity);
        // add column control
        if ($('th', g.hDiv).length) {
            g.nDiv.className = 'nDiv';
            g.nDiv.innerHTML = "<table cellpadding='0' cellspacing='0'><tbody></tbody></table>";
            $(g.nDiv).css({
                marginBottom: (gh * -1),
                display: 'none',
                top: gtop
            }).noSelect();
            var cn = 0;
            $('th div', g.hDiv).each(function () {
                // se la colonna è invisibile non mostro nemmeno il check di selezione
                if ($(p.colModel[cn]).attr('hide') == false
                || $(p.colModel[cn]).attr('hide') == undefined) {
                    var kcol = $("th[axis='col" + cn + "']", g.hDiv)[0];
                    var chk = 'checked="checked"';
                    if (kcol.style.display == 'none') {
                        chk = '';
                    }
                    $('tbody', g.nDiv).append('<tr><td class="ndcol1"><input type="checkbox" ' + chk + ' class="togCol" value="' + cn + '" /></td><td class="ndcol2">' + this.innerHTML + '</td></tr>');
                }
                cn++;
            });
            if ($.browser.msie && $.browser.version < 7.0) $('tr', g.nDiv).hover(function () {
                $(this).addClass('ndcolover');
            }, function () {
                $(this).removeClass('ndcolover');
            });
            $('td.ndcol2', g.nDiv).click(function () {
                if ($('input:checked', g.nDiv).length <= p.minColToggle && $(this).prev().find('input')[0].checked) return false;
                return g.toggleCol($(this).prev().find('input').val());
            });
            $('input.togCol', g.nDiv).click(function () {
                if ($('input:checked', g.nDiv).length < p.minColToggle && this.checked == false) return false;
                $(this).parent().next().trigger('click');
            });
            $(g.gDiv).prepend(g.nDiv); //lista delle colonne (chek per la visualizzazione)
            $(g.nBtn).addClass('nBtn')
				.html('<div style="height: inherit;"></div>')
				.attr('title', 'Hide/Show Columns')
				.click(function () {
				    $(g.nDiv).toggle();
				    return true;
				}
			);
            if (p.showColumnToggleBtn) {
                $(g.gDiv).prepend(g.nBtn); //div dei check per visualizzare le colonne (in questo momento è vuoto)
            }
        }
        // add date edit layer
        $(g.iDiv).addClass('iDiv').css({
            display: 'none'
        });
        $(g.bDiv).append(g.iDiv);  //div vuoto non so
        // add irongrid events
        $(g.bDiv).hover(function () {
            $(g.nDiv).hide();
            $(g.nBtn).hide();
        }, function () {
            //            if (g.multiSel) {
            //                g.multiSel = false;
            //            }
        });
        $(g.gDiv).hover(function () { }, function () {
            $(g.nDiv).hide();
            $(g.nBtn).hide();
        });
        //add document events
        $(document).mousemove(function (e) {
            g.dragMove(e)
        }).mouseup(function (e) {
            g.dragEnd()
        }).hover(function () { }, function () {
            g.dragEnd()
        });
        //browser adjustments
        if ($.browser.msie && $.browser.version < 7.0) {
            $('.hDiv,.bDiv,.mDiv,.pDiv,.vGrip,.tDiv, .sDiv', g.gDiv).css({
                width: '100%'
            });
            $(g.gDiv).addClass('ie6');
            if (p.width != 'auto') {
                $(g.gDiv).addClass('ie6fullwidthbug');
            }
        }
        g.rePosDrag();
        g.fixHeight();
        //make grid functions accessible
        t.p = p;
        t.grid = g;
        // load data
        if (p.url && p.autoload) {
            g.populate();
        }
        //altre opzioni
        //toggle on startup
        if (p.toggleTableOnStartup == true) {
            //g.slideToggle()
            $(toggleButton, g.mDiv).toggleClass('vsble');
            $(g.gDiv).toggleClass('hideBody');
            p.closed = true;

            $(g.gDiv).children('#ironGridBody, #ironGridToolbar, #ironGridHeader, #ironGridBody').animate({
                opacity: 'toggle',
                height: 'toggle'
            }, 0, function () {
            });

            if (p.usepager) {//se il non esistepager esiste salto
                $(g.gDiv).children('#ironGridPager').animate({
                    opacity: 'toggle',
                    height: 'toggle'
                }, 0, function () {
                });
            }
            if ($(g.sDiv)[0].open) { //se la rierca non era stata aperta salto
                $(g.gDiv).children('#ironGridSearch').animate({
                    opacity: 'toggle',
                    height: 'toggle'
                }, 0, function () {
                });
            }
        }
        return t;
    };
    var docloaded = false;
    $(document).ready(function () {
        docloaded = true
    });
    $.fn.irongrid = function (p) {
        return this.each(function () {
            if (!docloaded) {
                $(this).hide();
                var t = this;
                $(document).ready(function () {
                    $.addIron(t, p);
                });
            } else {
                $.addIron(this, p);
            }
        });
    }; //end irongrid

    $.fn.disableTopButton = function (disable) { // function to reload grid
        return this.each(function () {
            if (this.grid) { this.grid.disableTopButton(disable) }
        });
    }; //end disableButton

    $.fn.disableSearch = function (disable) { // function to reload grid
        return this.each(function () {
            if (this.grid) { this.grid.disableSearch(disable) }
        });
    }; //end disableButton

    $.fn.disablePager = function (disable) { // function to reload grid
        return this.each(function () {
            if (this.grid) {
                if (this.grid) { this.grid.disablePager(disable) }
            }
        });
    }; //end disablePager
    $.fn.disable = function (disable) { // function to reload grid
        return this.each(function () {
            if (this.grid) {
                if (this.grid) { this.grid.disable(disable) }
            }
        });
    }; //end disable

    $.fn.reload = function (p) { // function to reload grid
        return this.each(function () {
            if (this.p.url != p.url) { this.p.url = p.url; }
            if (this.grid && this.p.url) this.grid.populate();
        });
    }; //end reload
    $.fn.setOptions = function (p) { //function to update general options
        return this.each(function () {
            if (this.grid) { $.extend(this.p, p); }
        });
    }; //end options
    $.fn.getOptions = function (p) { //function to get general options
        var ret = undefined;

        this.each(function () {
            if (this.grid) {
                ret = $(this.p).attr(p);
            }
        });
        return ret;
    }; //end getoptions
    $.fn.getTitleHeight = function (p) { //function to get height of title
        var ret = 0
        this.each(function () {
            if (this.grid) {
                ret = $(this.grid.mDiv).css('height').replace('px', '');
            }
        });
        return ret;
    }; //end getTitleHeight    
    $.fn.getPagerHeight = function (p) { //function to get height of pager
        var ret = 0
        this.each(function () {
            if (this.grid) {
                ret = $(this.grid.pDiv).css('height').replace('px', '');
            }
        });
        return ret;
    }; //end getPagerHeight
    $.fn.getHeight = function (p) { //function to get height total grid (pager and title compresi)
        var ret = 0
        this.each(function () {
            if (this.grid) {
                var hContainer = $(this.grid.gDiv).css('height').replace('px', '');
                var hBody = $(this.grid.bDiv).css('height').replace('px', '')
                ret = $(this.grid.gDiv).css('height').replace('px', '');
                if (parseFloat(hContainer) > parseFloat(hBody)) { ret = hBody; }
            }
        });
        return ret;
    }; //end getPagerHeight


    $.fn.toggleCol = function (cid, visible) { // function to reload grid
        return this.each(function () {
            if (this.grid) this.grid.toggleCol(cid, visible);
        });
    }; //end toggleCol
    $.fn.addData = function (data) { // function to add data to grid
        return this.each(function () {
            if (this.grid) this.grid.addData(data);
        });
    };
    // chiude o apre la griglia
    $.fn.toggleTable = function () {
        return this.each(function () {
            if (this.grid) {
                $('div.ptogtitle', this.grid.mDiv).click();
            }
        });
    };

    $.fn.rowsSelected = function () { //get json object from rose selected
        var ret = 0;

        this.each(function () {
            if (this.grid) {
                ret = $('.trSelected', this).length;
            }
        });
        return ret;
    }; //end getSelectedRows

    $.fn.getSelectedRows = function (objStructure) { //torna una variabile json se objstructure è undefinied torna la struttura della tabella (colonne), altrimenti carica la struttra passata con le colonne scelte
        var ret = undefined;

        this.each(function () {
            if (this.grid) {
                var grid = this.grid;

                if (objStructure != undefined) {
                    var jSons = new Array()
                    var p = { name: '', value: '' };

                    $('.trSelected', this).each(function () {
                        row = this
                        var jSon = {};
                        $(objStructure).each(function () {
                            jSon[this.name] = $('td:eq(' + $('th', grid.hDiv).index($('th[abbr="' + this.value + '"]')) + ') > div', row).text();
                        });

                        jSons.push(jSon);
                    });
                    ret = jSons;
                } else {
                    var jSons = new Array()

                    $('.trSelected', this).each(function () {
                        var jSon = {};
                        $('td', $(this)).each(function () {
                            var colIDX = $('td', $(this).parent()).index(this)
                            var fieldName = $('th:eq(' + colIDX + ')', grid.hDiv).attr('abbr');
                            if (fieldName != undefined) {
                                jSon[fieldName] = $.trim($('> div', $(this)).text());
                            }
                        });
                        jSons.push(jSon);
                    });
                    ret = jSons;
                }
            }
        });
        return ret;
    }; //end getSelectedRows
    $.fn.selectedRowsContains = function (name, value) { //verifica se all'interno delle righe selezionate esiste un testo 
        var ret = false;

        this.each(function () {
            if (this.grid) {
                var grid = this.grid;
                var colIDX = $('th', grid.hDiv).index($('th[abbr="' + name + '"]'))

                ret = $('td:eq(' + colIDX + ') > div', $('.trSelected', grid.bDiv)).filter(function () {
                    var val = $(this).html()
                    val = val.replace('&nbsp;', '');
                    if (value == '') {
                        return val == '';
                    } else {
                        return val.indexOf(value) !== -1;
                    }
                }).length > 0
            }
        });
        return ret;
    }; //end getSelectedRows
    $.fn.toggleSelectRow = function (idRow) {
        return this.each(function () {
            if (this.grid) {
                $($(this.grid.bDiv).find('tr')[idRow]).toggleClass('trSelected');
            }
        });
    };

    $.fn.selectRow = function (idRow, select) {
        return this.each(function () {
            if (this.grid) {
                if (select) {
                    $($(this.grid.bDiv).find('tr')[idRow]).addClass('trSelected');
                } else {
                    $($(this.grid.bDiv).find('tr')[idRow]).removeClass('trSelected');
                }

            }
        });
    };

    $.fn.toggleSelectRows = function () {
        return this.each(function () {
            if (this.grid) {
                $($(this.grid.bDiv).find('tr')).toggleClass('trSelected');
            }
        });
    };

    $.fn.selectRows = function (select) {
        return this.each(function () {
            if (this.grid) {
                if (select) {
                    $($(this.grid.bDiv).find('tr')).addClass('trSelected');
                } else {
                    $($(this.grid.bDiv).find('tr')).removeClass('trSelected');
                }
            }
        });
    };

    //end toggletable

    $.fn.noSelect = function (p) { //no select plugin by me :-)
        var prevent = (p == null) ? true : p;
        if (prevent) {
            return this.each(function () {
                if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
                    return false;
                });
                else if ($.browser.mozilla) {
                    $(this).css('MozUserSelect', 'none');
                    $('body').trigger('focus');
                } else if ($.browser.opera) $(this).bind('mousedown', function () {
                    return false;
                });
                else $(this).attr('unselectable', 'on');
            });
        } else {
            return this.each(function () {
                if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
                else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
                else if ($.browser.opera) $(this).unbind('mousedown');
                else $(this).removeAttr('unselectable', 'on');
            });
        }
    }; //end noSelect
})(jQuery);

